package com.ruoyi.file.service;

import com.amazonaws.AmazonClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.uuid.Seq;
import com.ruoyi.file.config.MinioConfig;
import com.ruoyi.file.config.OssConfig;
import com.ruoyi.file.utils.FileUploadUtils;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Primary
@Service
public class CloudOssServiceImpl implements ISysFileService {
    @Autowired
    private OssConfig ossConfig;

    @Autowired
    private AmazonS3 ossClient;

    private static final Logger log = LoggerFactory.getLogger(CloudOssServiceImpl.class);


    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file,Integer authId) {
        try {
            long uid = Seq.getId();
            String fileName = FileUploadUtils.extractFilename(file);
            String key = uid + fileName.substring(fileName.lastIndexOf("."));
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            InputStream is = file.getInputStream();
            PutObjectRequest putObjectRequest = new PutObjectRequest(ossConfig.getBucketName(), key, is, metadata);
            if(authId == null || authId == 0){
                putObjectRequest.withCannedAcl(CannedAccessControlList.Private);
            }else if(authId == 1){
                putObjectRequest.withCannedAcl(CannedAccessControlList.PublicRead);
            }
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            log.info("OSS upload result: ContentMd5:{},ETaga:{},Metadata:{}", result.getContentMd5(), result.getETag(), result.getMetadata());
            return key;
        } catch (AmazonClientException | IOException e) {
            log.error("OSS upload Exception,msg:{}", e.getMessage());
            return null;
        }
    }


    @Override
    public byte[] downloadFile(String bucketName, String fileName, HttpServletResponse response) {
        InputStream stream = null;
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            if (StringUtils.isEmpty(bucketName))
                bucketName = ossConfig.getBucketName();
            S3Object object = ossClient.getObject(new GetObjectRequest(bucketName, fileName));
            stream = object.getObjectContent();
            IOUtils.copyLarge(stream, outputStream);
            return outputStream.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            IOUtils.closeQuietly(stream);
        }
    }

    @Override
    public String getDownloadUrl(String url){
        return "https://" + ossConfig.getOutUrl() + "/" + ossConfig.getBucketName() + "/" + url;
    }

}
